import { addOrUpdateInvoiceApi } from "@/api/configCenter/invoicesManagement";
import type { UploadProps } from "ant-design-vue";
import { message, Upload } from "ant-design-vue";

export default function OperationHook(state: any) {
  const { visible, passData, type, formState, loading, formRef, emit } = state;
  const onFish = () => {
    console.log("onFish");
    console.log(visible.value);
  };

  const onSubmit = () => {
    formRef.value.validate().then(() => {
      loading.value = true;
      const fromData = new FormData();
      fromData.append("file", formState.file[0]);
      fromData.append("name", formState.name);

      if (type.value === 2) {
        fromData.append("id", passData.value.id);
      }

      addOrUpdateInvoiceApi(fromData)
        .then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            emit("submit");
          }
        })
        .finally(() => {
          loading.value = false;
        });
    });
  };
  const resetForm = () => {
    formRef.value.resetFields();
    emit("update:visible", false);
  };

  // 导入文件
  const uploadRequestHandle = (e: any) => {
    formState.file = [e.file];
    e.onProgress({ percent: 100 });
  };

  const beforeUpload: UploadProps["beforeUpload"] = file => {
    const imageType = ["application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"].includes(file.type);
    const size = file.size / 1024 / 1024 > 500;
    return new Promise(resolve => {
      if (size) {
        message.error("文件大小不能超过500M!");
        return !size || Upload.LIST_IGNORE;
      }
      if (!imageType) {
        message.error("只能上传xls、xlsxw文件!");
        return !imageType || Upload.LIST_IGNORE;
      }
      resolve();
    });
  };
  return {
    onFish,
    resetForm,
    onSubmit,
    uploadRequestHandle,
    beforeUpload
  };
}
